


let Texture2D = require('../texture2d');
let SpriteFrame = require('./spriteFrame');
let JXON = require('jxon');

/**
 *  管杀不管埋
 */
class AssetCache{

    constructor() {
        this._texCaches = {};
        this._frameCache = {};
    }

    loadImage(imgPath){
        if(this._texCaches[imgPath]){
            console.warn(`already loaded:${imgPath}`);
            return;
        }

        let self = this;
        let img = new Image();
        img.src = imgPath;
        img.onload = function () {
            let tex2d = self._texCaches[imgPath] = new Texture2D(img);

            //  同时创建一个 spriteFrame
            let frame = new SpriteFrame(imgPath,tex2d,0,0,tex2d.width,tex2d.height);
            self._frameCache[imgPath] = frame;
        };
        img.onerror = function (err) {
            console.error(`load imgPath:${imgPath} error!`);
            throw err;
        };
    }

    loadAtlas(plistPath){
        let xhr = new XMLHttpRequest();
        xhr.timeout = 5000;
        xhr.responseType = 'text';
        xhr.onload = function () {
            let text = xhr.responseText;
            let jsObj = JXON.stringToJs(text);
            console.log('jsObj:',jsObj);
        };
        xhr.onerror = function () {
            console.error(`load plist:${plistPath} error!`);
        };
        xhr.open('GET',plistPath);
        xhr.send();

    }

    getSpriteFrame(frameName){
        return this._frameCache[frameName];
    }
}

module.exports = AssetCache;